// 定义模块
layui.define([], function(exports){
    // 检测浏览器的兼容性，如果不支持则发出警告

    // 保存旧的xhr对象
    window._ahrealxhr = window._ahrealxhr || XMLHttpRequest;

    // 定义对象
    var obj = {
        // hook
        hook: function(funs) {
            XMLHttpRequest = function () {
                this.xhr = new window._ahrealxhr;
                for (var attr in this.xhr) {
                    var type = "";
                    try {
                        type = typeof this.xhr[attr]
                    } catch (e) {}
                    if (type === "function") {
                        this[attr] = hookfun(attr);
                    } else {
                        Object.defineProperty(this, attr, {
                            get: getFactory(attr),
                            set: setFactory(attr)
                        })
                    }
                }
            }

            function getFactory(attr) {
                return function () {
                    return this.hasOwnProperty(attr + "_")?this[attr + "_"]:this.xhr[attr];
                }
            }

            function setFactory(attr) {
                return function (f) {
                    var xhr = this.xhr;
                    var that = this;
                    if (attr.indexOf("on") != 0) {
                        this[attr + "_"] = f;
                        return;
                    }
                    if (funs[attr]) {
                        xhr[attr] = function () {
                            funs[attr](that) || f.apply(xhr, arguments);
                        }
                    } else {
                        xhr[attr] = f;
                    }
                }
            }

            function hookfun(fun) {
                return function () {
                    var args = [].slice.call(arguments)
                    if (funs[fun] && funs[fun].call(this, args, this.xhr)) {
                        return;
                    }
                    return this.xhr[fun].apply(this.xhr, args);
                }
            }
            return window._ahrealxhr;
        },

        // unhook
        unhook: function() {
            if (window._ahrealxhr)
                XMLHttpRequest = window._ahrealxhr;
            window._ahrealxhr = undefined;
        }
    }

    exports('ajaxhook', obj);
});
